package com.j2eefast.web.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.j2eefast.common.core.utils.RedisUtil;
import com.j2eefast.web.common.BaseUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录服务
 */
@Service
public class LoginService {

    @Autowired
    private RedisUtil cacheUtil;

    private final static String USERNAME = "澳华牧业";
    private final static String PASSWORD = "ah24492*";

    private String TOKEN_KEY = "AI_YANG_NIU_TOKEN";

    public String getToken(){
        String token = cacheUtil.get(TOKEN_KEY);
        if(StrUtil.isEmpty(token)){
            doLogin();
        }else{
            volidateToken();
        }

        return cacheUtil.get(TOKEN_KEY);
    }

    private void volidateToken() {
        String url = BaseUrl.USER_INFO;
        String token = cacheUtil.get(TOKEN_KEY);
        if(StrUtil.isEmpty(token)){
            doLogin();
            return;
        }

        String res = HttpRequest.get(url).header("X-AIYANGNIU-SIGNATURE",token)
                .execute().body();

        JSONObject data = JSONUtil.parseObj(res);
        if(data == null || !data.getInt("code").equals(101)){
            doLogin();
        }
    }

    private void doLogin() {
        String url = BaseUrl.LOGIN_URL;
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("username",USERNAME);
        paramMap.put("password",PASSWORD);
        paramMap.put("sensorsType",1);
        String result = HttpUtil.post(url,paramMap);

        JSONObject data = JSONUtil.parseObj(result);
        if(data != null && data.getInt("code").equals(101)){
            cacheUtil.set(TOKEN_KEY,data.getStr("data"));
        }else{
        }
    }
}
